package com.seednia.module.core.profile.command;

import java.util.List;

import org.apache.commons.chain.Command;
import org.apache.commons.chain.Context;

import com.seednia.foundation.framework.dto.QueryParams;
import com.seednia.foundation.framework.extension.command.CommandContext;
import com.seednia.foundation.framework.service.ServiceContainer;
import com.seednia.foundation.framework.util.NumberUtils;
import com.seednia.module.core.profile.dto.ProfileCriteria;
import com.seednia.module.core.profile.dto.ProfileDto;
import com.seednia.module.core.profile.service.IProfileService;

public class LoadProfileWithConnCommand implements Command{

	private IProfileService profileService;
	
	
	
	public IProfileService getProfileService() {
		if (profileService == null)
			profileService = ServiceContainer.getInstance().getByType(IProfileService.class);
		return profileService;
	}
	public void setProfileService(IProfileService profileService) {
		this.profileService = profileService;
	}



	@Override
	public boolean execute(Context context) throws Exception {

		CommandContext cmdContext = (CommandContext)context;
		
		Long userSid = NumberUtils.toLong(cmdContext.getQueryParams().get("userSid", null));
		if (userSid == null)
			throw new IllegalArgumentException("Missing userSid");
		
		// This is optional
		Long projectSid = NumberUtils.toLong(cmdContext.getQueryParams().get("projectSid", null));

		// This is required (Notice it is from cmdContext, as it is sent by immediate caller)
		Long profileSid = (Long)cmdContext.get("sid");

		ProfileCriteria profileCriteria = new ProfileCriteria();
		profileCriteria.setSid(profileSid);
		
		List<ProfileDto> result = getProfileService().getProfileWithConn(cmdContext.getRequestContext(), profileCriteria, userSid, projectSid, new QueryParams(0,2));
		if (result != null && result.size() > 0) {
			cmdContext.setRecord(result.get(0));
		}
		
		return false;
	}

}
